package com.scnu.edu.controller;

import com.scnu.edu.dto.MovieDTO;
import com.scnu.edu.entity.Movie;
import com.scnu.edu.entity.PlayRecord;
import com.scnu.edu.entity.Rating;
import com.scnu.edu.entity.User;
import com.scnu.edu.service.MovieService;
import com.scnu.edu.service.PlayRecordService;
import com.scnu.edu.service.RatingService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {
    @Resource
    private MovieService movieService;
    
    @Resource
    private PlayRecordService playRecordService;
    
    @Resource
    private RatingService ratingService;

    @RequestMapping({"/", ""})
    public String index(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !user.getIsAdmin()) {
            return "redirect:/login";
        }
        return "admin/index";
    }

    @RequestMapping("/export/ranking")
    public void exportRanking(HttpServletResponse response) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("电影排行榜");
        
        // 创建表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("排名");
        headerRow.createCell(1).setCellValue("电影ID");
        headerRow.createCell(2).setCellValue("电影名称");
        headerRow.createCell(3).setCellValue("播放次数");
        
        // 获取排行榜数据
        List<MovieDTO> ranking = movieService.getAllTimeRanking();
        
        // 填充数据
        int rowNum = 1;
        for (MovieDTO movie : ranking) {
            Row row = sheet.createRow(rowNum++);
            row.createCell(0).setCellValue(rowNum - 1);
            row.createCell(1).setCellValue(movie.getId());
            row.createCell(2).setCellValue(movie.getName());
            row.createCell(3).setCellValue(movie.getPlayCount());
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        // 生成带时间戳的文件名
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = dateFormat.format(new Date());
        String fileName = "电影排行榜_" + timestamp + ".xlsx";

        // 对文件名进行编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replace("+", "%20");

        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        // 写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    
    @RequestMapping("/export/movie/{movieId}/{type}")
    public void exportMovieData(@PathVariable Long movieId,
                              @PathVariable String type,
                              HttpServletResponse response,
                              HttpSession session) throws IOException {
        User user = (User) session.getAttribute("user");
        if (user == null || !user.getIsAdmin()) {
            return;
        }

        Movie movie = movieService.getById(movieId);
        if (movie == null) {
            return;
        }

        Workbook workbook = new XSSFWorkbook();
        
        if ("play".equals(type)) {
            Sheet sheet = workbook.createSheet("播放记录");
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("用户ID");
            headerRow.createCell(1).setCellValue("播放时间");
            headerRow.createCell(2).setCellValue("播放时长（秒）");
            
            List<PlayRecord> records = playRecordService.getPlayRecordsByMovieId(movieId);
            int rowNum = 1;
            for (PlayRecord record : records) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(record.getUserId());
                row.createCell(1).setCellValue(record.getCreateTime().toString());
                row.createCell(2).setCellValue(record.getDuration());
            }
        } else if ("comment".equals(type)) {
            Sheet sheet = workbook.createSheet("评论记录");
            Row headerRow = sheet.createRow(0);
            headerRow.createCell(0).setCellValue("用户ID");
            headerRow.createCell(1).setCellValue("评分");
            headerRow.createCell(2).setCellValue("评论时间");
            
            List<Rating> ratings = ratingService.getRatingsByMovieId(movieId);
            int rowNum = 1;
            for (Rating rating : ratings) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(rating.getUserId());
                row.createCell(1).setCellValue(rating.getScore());
                row.createCell(2).setCellValue(rating.getCreateTime().toString());
            }
        }



        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

        // 生成带时间戳的文件名
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = dateFormat.format(new Date());
        String fileName = "电影报表_"+ movie.getName()+"_"+ timestamp + ".xlsx";

        // 对文件名进行编码
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()).replace("+", "%20");

        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        // 写入响应流
        workbook.write(response.getOutputStream());
        workbook.close();
    }
    
    @RequestMapping("/movies")
    public String movies(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                        @RequestParam(name = "title", defaultValue = "") String title,
                        Model model,
                        HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !user.getIsAdmin()) {
            return "redirect:/login";
        }

        Integer pageSize = 10;
        Map<String, Object> map = movieService.queryPage(title, "", pageNo, pageSize);
        
        model.addAttribute("movies", map.get("records"));
        model.addAttribute("currentPage", pageNo);
        model.addAttribute("pageCount", map.get("pageCount"));
        model.addAttribute("title", title);
        return "admin/movies";
    }

    @RequestMapping("/movie/save")
    @ResponseBody
    public String saveMovie(Movie movie, 
                          @RequestParam(name = "categoryIds", required = false) List<Long> categoryIds,
                          HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !user.getIsAdmin()) {
            return "无权限操作";
        }

        if (movieService.saveOrUpdate(movie)) {
            // 保存分类关联
            if (categoryIds != null && !categoryIds.isEmpty()) {
                movieService.updateMovieCategories(movie.getId(), categoryIds);
            }
            return "保存成功";
        } else {
            return "保存失败";
        }
    }

    @RequestMapping("/movie/{id}")
    @ResponseBody
    public MovieDTO getMovieWithCategories(@PathVariable Long id) {
        MovieDTO movieDTO = movieService.getMovieDTOById(id);
        // 获取分类ID列表
        List<Long> categoryIds = movieService.getCategoryIdsByMovieId(id);
        movieDTO.setCategoryIds(categoryIds);
        return movieDTO;
    }

    @RequestMapping("/movie/delete")
    @ResponseBody
    public String deleteMovie(Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null || !user.getIsAdmin()) {
            return "无权限操作";
        }

        if (movieService.removeById(id)) {
            return "删除成功";
        } else {
            return "删除失败";
        }
    }


    private void createRankingSheet(Workbook workbook, String sheetName, List<MovieDTO> movies) {
        Sheet sheet = workbook.createSheet(sheetName);
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("排名");
        headerRow.createCell(1).setCellValue("电影名称");
        headerRow.createCell(2).setCellValue("播放次数");
        headerRow.createCell(3).setCellValue("评分");
        headerRow.createCell(4).setCellValue("上映时间");

        for (int i = 0; i < movies.size(); i++) {
            MovieDTO movieDTO = movies.get(i);
            Row row = sheet.createRow(i + 1);
            row.createCell(0).setCellValue(i + 1);
            row.createCell(1).setCellValue(movieDTO.getName());
            row.createCell(2).setCellValue(movieDTO.getPlayCount());
            row.createCell(3).setCellValue(movieDTO.getScore());
            row.createCell(4).setCellValue(movieDTO.getReleaseDate());
        }

        // 自动调整列宽
        for (int i = 0; i < 5; i++) {
            sheet.autoSizeColumn(i);
        }
    }
}